package com.zf.shuashua.utils;


import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class TimeUtils {


    /**
     * 通过时间秒毫秒数判断两个时间的间隔
     *
     * @param date1
     * @param date2
     * @return
     */
    public static int differentDaysByMillisecond(Date date1, Date date2) {
        int days = (int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24));
        return days;
    }

    /**
     * 判断time是否在from，to之内
     * 精确到分
     *
     * @param time 当前时间
     * @param from 开始日期
     * @param from 结束日期
     * @return
     */
    public static boolean isEffectiveDate(Date time, long from, long to) {
        return belongCalendar(time, new Date(from * 1000), new Date(to * 1000));
    }

    /**
     * 判断time是否在from，to之内
     *
     * @param time 指定日期
     * @param from 开始日期
     * @param to   结束日期
     * @return
     */
    public static boolean belongCalendarStr(Date time, String from, String to) {
        return belongCalendar(time, strToDate(from), strToDate(to));
    }

    /**
     * 判断time是否在from，to之内
     *
     * @param time 指定日期
     * @param from 开始日期
     * @param to   结束日期
     * @return
     */
    public static boolean belongCalendar(Date time, Date from, Date to) {
        if(time == null || from == null || to == null){
            return false;
        }

        Calendar date = Calendar.getInstance();
        date.setTime(time);

        Calendar after = Calendar.getInstance();
        after.setTime(from);

        Calendar before = Calendar.getInstance();
        before.setTime(to);

        if (date.after(after) && date.before(before)) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 日期转换成字符串
     *
     * @param date
     * @return str
     */
    public static String dateToStr(Date date) {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");//日期格式
        String str = format.format(date);
        return str;
    }

    /**
     * 字符串转换成日期
     *
     * @param time
     * @return date
     */
    public static Date strToDate(String time) {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");//日期格式
        Date date = null;
        try {
            date = format.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

}